package org.wmq.Mapper.impl;

import com.alibaba.fastjson.JSON;
import org.wmq.Cache.LocalCache;
import org.wmq.Mapper.CommentMapper;
import org.wmq.model.Entity.MySimpleMap;
import org.wmq.model.Entity.MySimpleMapComment;

import java.io.*;
import java.net.FileNameMap;
import java.time.LocalDateTime;

public class CommentMapperImpl implements CommentMapper {
    private static final String COMMENT_FILE_PREFIX = "D:\\map_collection_data\\comment_data";
    private static final String COMMENT_FILE_SUFFIX = ".txt";
    @Override
    public boolean setCommentByMySimpleMapId(Long mySimpleMapId, String content) throws IOException {
        MySimpleMapComment comment = new MySimpleMapComment();
        comment.setMySimpleMapId(mySimpleMapId);
        comment.setComment(content);
        return this.insert(comment);
    }

    @Override
    public MySimpleMapComment selectByMySimpleMapId(Long mySimpleMap) throws IOException {
        String filename = COMMENT_FILE_PREFIX + "\\"
                + mySimpleMap + COMMENT_FILE_SUFFIX;
        File file = new File(filename);
        if (!file.exists()){
            System.out.println("文件不存在");
            return null;
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        String JsonString = new String(fileInputStream.readAllBytes());
        MySimpleMapComment result = JSON.parseObject(JsonString, MySimpleMapComment.class);
        fileInputStream.close();
        return result;
    }

    @Override
    public boolean updateByMySimpleMapId(MySimpleMapComment comment) throws IOException {
        String filename = COMMENT_FILE_PREFIX + "\\" +
                comment.getMySimpleMapId() + COMMENT_FILE_SUFFIX;
        File file = new File(filename);
        if (file.exists()){
            file.delete();
        }
        return this.insert(comment);
    }

    @Override
    public boolean deleteByMySimpleMapId(Long mySimpleMapId) throws IOException {
        String filename = COMMENT_FILE_PREFIX + "\\"
                + mySimpleMapId + COMMENT_FILE_SUFFIX;
        File file = new File(filename);
        if (!file.exists()){
            System.out.println("文件不存在");
            return false;
        }
        file.delete();
        return true;
    }

    public boolean insert(MySimpleMapComment comment) throws IOException {
        String filename = COMMENT_FILE_PREFIX + "\\"
                + comment.getMySimpleMapId() + COMMENT_FILE_SUFFIX;
        File file = new File(filename);
        if (file.exists()){
            System.out.println("当前文件已经存在");
            return false;
        }
        String jsonString = JSON.toJSONString(comment);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(jsonString.getBytes());
        fileOutputStream.close();
        return true;
    }
}
